import { ansibleAPI } from '@/api/ansible'
import { ansibleModules, getModuleNames, getModuleParameters } from '@/data/ansibleModules.js'
import * as monaco from 'monaco-editor'

// 解析Ansible命令
export const parseAnsibleCommand = (text, position) => {
  const lines = text.split('\n')
  const currentLine = lines[position.lineNumber - 1]
  const beforeCursor = currentLine.substring(0, position.column - 1)

  // 检查是否是ansible命令
  if (!beforeCursor.trim().startsWith('ansible')) {
    return null
  }

  // 解析命令结构
  const parts = beforeCursor.split(/\s+/)
  const context = {
    command: parts[0], // ansible
    target: null,      // 目标主机/组
    module: null,      // 模块名
    args: null,        // 参数
    currentPart: null, // 当前正在输入的部分
    needsCompletion: null // 需要补全的类型
  }

  // 分析当前输入位置
  for (let i = 1; i < parts.length; i++) {
    const part = parts[i]

    if (i === 1 && !part.startsWith('-')) {
      // 第一个参数是目标
      context.target = part
    } else if (part === '-m' && i + 1 < parts.length) {
      // 模块参数
      context.module = parts[i + 1]
      i++ // 跳过下一个参数
    } else if (part === '-a' && i + 1 < parts.length) {
      // 模块参数
      context.args = parts.slice(i + 1).join(' ')
      break
    }
  }

  // 确定需要补全的类型

  if (beforeCursor.endsWith(' ')) {
    // 空格后，需要新的参数
    if (parts.length === 2) {
      // ansible 后面的空格，需要目标补全
      context.needsCompletion = 'target'
      context.currentPart = ''
    } else if (beforeCursor.includes('-m ') && !context.module) {
      // -m 后面的空格，需要模块补全
      context.needsCompletion = 'module'
      context.currentPart = ''
    } else if (beforeCursor.includes('-a ') && context.module) {
      // -a 后面的空格，需要参数补全
      context.needsCompletion = 'args'
      context.currentPart = ''
    } else if (!beforeCursor.includes('-m') && !beforeCursor.includes('-a')) {
      // 还没有-m和-a选项，提示选项
      context.needsCompletion = 'option'
      context.currentPart = ''
    }
  } else {
    // 正在输入中
    const lastPart = parts[parts.length - 1]
    if (parts.length === 2) {
      // 正在输入目标
      context.needsCompletion = 'target'
      context.currentPart = lastPart
    } else if (beforeCursor.includes('-m ') && !beforeCursor.includes('-a')) {
      // 正在输入模块
      context.needsCompletion = 'module'
      context.currentPart = lastPart
    } else if (beforeCursor.includes('-a ')) {
      // 正在输入参数
      context.needsCompletion = 'args'
      context.currentPart = lastPart
    }
  }

  return context
}

// 获取主机和主机组列表
let hostsCache = {}  // 改为对象，按inventory_id缓存
let groupsCache = {}
let cacheTime = {}
const CACHE_DURATION = 30000 // 30秒缓存

export const getHostsAndGroups = async (inventoryId = null) => {
  const now = Date.now()
  const cacheKey = inventoryId || 'default'

  // 检查缓存是否有效
  if (hostsCache[cacheKey] && groupsCache[cacheKey] && cacheTime[cacheKey] &&
      (now - cacheTime[cacheKey] < CACHE_DURATION)) {
    return {
      hosts: hostsCache[cacheKey],
      groups: groupsCache[cacheKey]
    }
  }

  try {
    let response
    let data

    if (inventoryId) {
      // 从指定的inventory获取主机和主机组
      response = await ansibleAPI.getHostsAndGroups(inventoryId)
      data = response.data.data
    } else {
      // 如果没有指定inventory，尝试从所有inventory解析
      response = await ansibleAPI.getInventories()
      const inventories = response.data.results || response.data || []

      const hosts = new Set()
      const groups = new Set()

      inventories.forEach(inventory => {
        if (inventory.content) {
          // 解析inventory内容
          const lines = inventory.content.split('\n')
          let currentGroup = null

          lines.forEach(line => {
            line = line.trim()
            if (!line || line.startsWith('#')) return

            // 检查是否是组定义
            if (line.startsWith('[') && line.endsWith(']')) {
              currentGroup = line.slice(1, -1)
              if (!currentGroup.includes(':')) {
                groups.add(currentGroup)
              }
            } else if (line.includes('=') || line.match(/^\S+$/)) {
              // 主机定义
              const hostName = line.split(/\s+/)[0].split('=')[0]
              if (hostName && !hostName.startsWith('[')) {
                hosts.add(hostName)
              }
            }
          })
        }
      })

      data = {
        hosts: Array.from(hosts).map(host => ({ name: host, hostname: host })),
        groups: Array.from(groups).map(group => ({ name: group }))
      }
    }

    hostsCache[cacheKey] = []
    groupsCache[cacheKey] = []

    // 处理主机组数据
    if (data.groups && Array.isArray(data.groups)) {
      groupsCache[cacheKey] = data.groups.map(group => group.name || group)
    }

    // 处理主机数据
    if (data.hosts && Array.isArray(data.hosts)) {
      hostsCache[cacheKey] = data.hosts.map(host => host.hostname || host.name || host)
    }

    cacheTime[cacheKey] = now
    console.log(`智能提示缓存更新 (inventory: ${inventoryId || 'all'}): ${hostsCache[cacheKey].length} 台主机, ${groupsCache[cacheKey].length} 个主机组`)

  } catch (error) {
    console.error('获取主机和组失败:', error)
    hostsCache[cacheKey] = []
    groupsCache[cacheKey] = []
  }

  return {
    hosts: hostsCache[cacheKey] || [],
    groups: groupsCache[cacheKey] || []
  }
}

// 生成目标补全建议
export const getTargetCompletions = async (currentPart = '', inventoryId = null) => {
  const { hosts, groups } = await getHostsAndGroups(inventoryId)
  const completions = []

  // 添加特殊目标
  const specialTargets = ['all', 'localhost']
  specialTargets.forEach(target => {
    if (!currentPart || target.startsWith(currentPart)) {
      completions.push({
        label: target,
        kind: 14, // Keyword
        detail: '特殊目标',
        insertText: target,
        documentation: target === 'all' ? '所有主机' : '本地主机'
      })
    }
  })

  // 添加主机组
  groups.forEach(group => {
    if (!currentPart || group.startsWith(currentPart)) {
      completions.push({
        label: group,
        kind: 9, // Module
        detail: '主机组',
        insertText: group,
        documentation: `主机组: ${group}`
      })
    }
  })

  // 添加主机
  hosts.forEach(host => {
    if (!currentPart || host.startsWith(currentPart)) {
      completions.push({
        label: host,
        kind: 6, // Variable
        detail: '主机',
        insertText: host,
        documentation: `主机: ${host}`
      })
    }
  })

  return completions
}

// 生成模块补全建议
export const getModuleCompletions = (currentPart = '') => {
  const moduleNames = getModuleNames()
  const completions = []

  moduleNames.forEach(moduleName => {
    if (!currentPart || moduleName.startsWith(currentPart)) {
      const moduleInfo = ansibleModules[moduleName]
      completions.push({
        label: moduleName,
        kind: 3, // Function
        detail: 'Ansible模块',
        insertText: moduleName,
        documentation: moduleInfo.description
      })
    }
  })

  return completions
}

// 生成参数补全建议
export const getArgsCompletions = (moduleName, currentPart = '') => {
  const parameters = getModuleParameters(moduleName)
  const completions = []

  parameters.forEach(param => {
    if (!currentPart || param.startsWith(currentPart)) {
      completions.push({
        label: param,
        kind: 10, // Property
        detail: `${moduleName}模块参数`,
        insertText: param,
        documentation: `${moduleName}模块的参数: ${param}`
      })
    }
  })

  return completions
}

// 生成选项补全建议
export const getOptionCompletions = (currentPart = '') => {
  const options = [
    { label: '-m', detail: '指定模块', insertText: '-m ' },
    { label: '-a', detail: '模块参数', insertText: '-a ' },
    { label: '-i', detail: '指定inventory文件', insertText: '-i ' },
    { label: '-u', detail: '指定用户', insertText: '-u ' },
    { label: '-k', detail: '询问密码', insertText: '-k' },
    { label: '--ask-pass', detail: '询问密码', insertText: '--ask-pass' },
    { label: '--private-key', detail: '私钥文件', insertText: '--private-key ' },
    { label: '-f', detail: '并发数', insertText: '-f ' },
    { label: '--forks', detail: '并发数', insertText: '--forks ' },
    { label: '-v', detail: '详细输出', insertText: '-v' },
    { label: '-vv', detail: '更详细输出', insertText: '-vv' },
    { label: '-vvv', detail: '最详细输出', insertText: '-vvv' },
    { label: '--check', detail: '检查模式', insertText: '--check' },
    { label: '--diff', detail: '显示差异', insertText: '--diff' },
    { label: '-o', detail: '单行输出', insertText: '-o' },
    { label: '--one-line', detail: '单行输出', insertText: '--one-line' },
    { label: '-T', detail: '连接超时', insertText: '-T ' },
    { label: '--timeout', detail: '连接超时', insertText: '--timeout ' }
  ]

  return options
    .filter(option => !currentPart || option.label.startsWith(currentPart))
    .map(option => ({
      ...option,
      kind: 14, // Keyword
      documentation: option.detail
    }))
}

// 主要的补全提供函数
export const provideCompletions = async (model, position, inventoryId = null) => {
  const text = model.getValue()
  const context = parseAnsibleCommand(text, position)

  console.log('智能提示触发 - 文本:', text, '位置:', position, '解析上下文:', context, 'inventory ID:', inventoryId)

  if (!context) {
    console.log('没有解析到ansible命令上下文，提供基础补全')
    // 如果不是ansible命令，提供基础的ansible命令补全
    const word = model.getWordUntilPosition(position)
    const range = {
      startLineNumber: position.lineNumber,
      endLineNumber: position.lineNumber,
      startColumn: word.startColumn,
      endColumn: word.endColumn
    }

    return {
      suggestions: [
        {
          label: 'ansible',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'ansible all -m ping',
          documentation: 'Ansible ad-hoc命令',
          detail: '基础命令',
          range: range
        },
        {
          label: 'ansible-playbook',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'ansible-playbook playbook.yml',
          documentation: 'Ansible playbook执行',
          detail: 'Playbook命令',
          range: range
        }
      ]
    }
  }

  let completions = []

  switch (context.needsCompletion) {
    case 'target':
      console.log('获取目标补全，当前部分:', context.currentPart, 'inventory ID:', inventoryId)
      completions = await getTargetCompletions(context.currentPart, inventoryId)
      console.log('目标补全结果:', completions)
      break
    case 'module':
      completions = getModuleCompletions(context.currentPart)
      break
    case 'args':
      completions = getArgsCompletions(context.module, context.currentPart)
      break
    case 'option':
      completions = getOptionCompletions(context.currentPart)
      break
  }

  console.log('生成的补全建议:', completions)
  return { suggestions: completions }
}
